ColdFusion Article

InTouch: Permission-Based E-mail Marketing Application

If anything, e-mail has become quintessential to our existence today. Corporations, organizations, politicians, and all kinds of others use e-mail successfully to keep "in touch" with their constituents and customers. However, the process of maintaining lists can be cumbersome as people change e-mail addresses and companies maintain multiple lists that may even draw upon different user databases.

Enter InTouch. This sample application allows list managers to set up and maintain multiple lists, send e-mails in HTML and text formats, find bad e-mail addresses, and allow users to select their preferred format, subscribe/unsubscribe from lists, and more. In developing InTouch, we have aimed to create as universal an application as possible. The <CFMAIL> update in ColdFusion MX 6.1 Enterprise allows you to send thousands of e-mails in less time than ever.

Additionally, the subscription management (un/subscribe) features are offered as a web service or CFC so you can use existing forms to perform these processes.

Installing InTouch

InTouch is a fairly straightforward ColdFusion application to install and set up:

  1. Extract the contents of the ZIP file to the root (or subfolder) of your ColdFusion server.
  2. Map a JDBC datasource in the ColdFusion Administrator (called "intouch" by default) to the {intouch_root}/database/PBEMT.mdb database.
  3. Launch InTouch in your browser. If you installed it to the InTouch folder at the ColdFusion root, this would be http://localhost:8500/intouch/. The default login information is admin/admin.
  4. Go to the Global Settings screen and enter the appropriate information for your server.

Administering InTouch

The InTouch administrator is where list managers can manage this application. The administrator is broken into the following categories:

  • Global Settings: The main defaults and application settings can be modified
  • List Management: Create/edit/delete lists, as well as see returned e-mails and remove those users from lists
  • Messages and Templates: Create new messages, create/edit/delete message templates, and send messages
  • Users and Groups: Use the database built into the system to store list subscribers if preferred, otherwise use it to add administrative users into the InTouch administrator

Global Settings

The Global Settings screen (see Figure 1) in InTouch allows administrators to set application defaults.

The InTouch Global Settings screen

Figure 1. The InTouch Global Settings screen

From a ColdFusion developer's standpoint, these are simply application variables. Making changes to these settings changes the values of the application variables in memory and also saves an XML file ({intouch_root}/includes/application.wddx) that the server uses to reserialize these variables. These variables perform the following functions:

  • List Datasource: This should be the DSN name (as set in the ColdFusion Administrator) that contains the list information—either PBEMT.mdb, which comes with this application, or the same tables as imported or recreated in another datasource.
  • Default User Datasource: While the accompanying datasource includes a users table, it is entirely likely that you would want to use another datasource as the primary user database—specifically an existing customer, vendor, or partner database. You can add datasources on a list-by-list basis, which is one of this application's strengths. This setting variable is the default. To use the built-in user table, this should be the same value as the list datasource.
  • Default User Table: When defining an outside datasource, it is also important to define the table where the user data is stored. This table must exist in the default user datasource or else errors will invariably occur. The users table in the InTouch database is called Users.
  • Default User ID Field: In order to link users within lists to the internal or external datasource/user table, the name of the unique identifier field for the users will need to be defined here. This field must exist in the default user table to function correctly. The user ID field in the InTouch database is UserID.
  • Default User Email Field: To allow for dynamic e-mailing from an external (as well as the internal) database, InTouch needs to know what field in the user table contains the e-mail address of the user. The e-mail field in the InTouch database is called Email.
  • Default E-mail Format: This sets the default format for users who have not defined the format in which they prefer to receive their e-mails. This is either text or HTML.
  • Rows to Show: This affects how many rows of data are displayed in the InTouch administrator. For example, if this is set to 20, you will view 20 users at a time, 20 e-mail lists, etc.
  • Reply E-mail: This should be the e-mail address where returned messages are sent. It is recommended that you set up a separate account for these e-mails and provide links within your outgoing messages for recipients to contact you. If you do it this way, this account will receive bounce-backs that can be managed through the InTouch administrator.
  • Reply Label: Whatever is entered for this setting parameter is what appears in recipients' inboxes. You can enter your e-mail address, a company name, or whatever you wish recipients to see as the sender. E-mails are sent out in this format: <Reply Label> Reply Email.
  • Reply E-mail Server: This should be the SMTP server where the reply e-mail is located. This will be used to retrieve bounce-backs.
  • Reply E-mail Password: This is the password for the SMTP server for the reply e-mail and enables InTouch to log in and retrieve bounce-backs.

List Management

List management in InTouch is where you add, modify, and delete e-mail lists. There is no limit to how many lists you can store in InTouch. One of the great strengths of this application is that you can link lists to any datasource accessible using a JDBC/ColdFusion datasource. Through this administrator, you can create new list groups and import lists.

Two steps are required to create a new list:

  1. Add the list by defining the datasource, user table, user ID field, user e-mail field, and default e-mail format for this list. Also, give your list a name that helps you recognize it. These all function identically to their counterparts in the Global Settings screen: The datasource must be entered in the ColdFusion Administrator, the user table must exist in that datasource, and the user ID and e-mail fields must exist in the user table.
  2. Import users from the appropriate datasource at any time, as well as view information about the list. This is done by clicking the Edit Lists link and then clicking the name of the list you wish to see. You can edit any information about the list, view list statistics (number of active/inactive users and number of users receiving text/HTML formatted messages), and import users (see Figure 2).

    Note: Simply adding a list does not import users. You must do this step separately.

    To import all users in the specified datasource, simply click the Import Users button. You can also use SQL to add an optional WHERE clause to filter which users to import. It is strongly recommended that you test a simple SELECT statement with your WHERE clause before running the import query here. Include the keyword WHERE in your query. An example of a filter might be:

    WHERE EmailListActive = 'Y'

The Edit List/Import Users screen

Figure 2: The Edit List/Import Users screen

Messages and Templates

Once you create your lists, you will likely want to send out messages. InTouch allows you to create message templates that you can use as the starting point for your messages. For example, if you manage a weekly newsletter, there is likely a format that you will want to use week after week, albeit with different articles and information. If you add this format as a template, you can use it whenever you send out your messages.

Creating and Editing Templates

Creating and editing templates is simply a matter of naming your template, selecting what format it is (text or HTML), and pasting your template into the template text field. If you are using HTML, make sure that any image references and links reference the full URL (such as http://www.yourdomain.com/yourresource.gif) because any absolute (starting with just /) or relative (../resourcename) URL will not appear in the user's e-mail.

Keep in mind that any message you use can dynamically insert information from your user database table. Simply enter the field name surrounded by percentage signs (for example, %FirstName%) and let InTouch do the rest. When creating templates, you can embed these dynamic fields directly into your templates.

To add a new template, click the templates link on the left navigation, click Add New Template, and enter the appropriate information. Editing is done by clicking the name of the template you wish to update on the main templates screen. To delete, simply check the box next to the appropriate template(s) and click the Delete Templates button.

Creating and Sending Messages

To send a message, start by clicking the new message link in the InTouch administrator. This brings you to the first step (of three) in the new message process:

  1. 1. Select the templates you wish to start with. If you want to start with blank messages, simply click the Create Message(s) button.
  2. 2. Enter the subject of the e-mail and the message for both text and HTML versions. It is not required that you enter messages for both. However, if any of your users have chosen to receive mail in a format for which you do not enter a message, they will receive a blank e-mail from you—so be careful. To learn how to view all users who subscribe to text/HTML editions, see the "List Management" section earlier in this article. When you are done, click the Select List(s) button. Keep in mind that any message you use can dynamically insert information from your user database table. Simply enter the field name surrounded by percentage signs (for example, %LastName%) and let InTouch do the rest.
  3. 3. Select the list(s) you would like to send this message to. To select multiple lists, hold down the Control key while clicking the list name; you can also deselect an item this way. You must select at least one list. You can review your messages in new windows by clicking the preview links. When you are ready, click the Send Message(s) button.

    Note: This will send the messages; you will not receive any additional screens. On the next screen, you should receive feedback as your messages are sent to the lists. You will see the number of each message (1, 2, 3, etc.) as it is sent as well as the number of each list as it begins.

Archiving Messages

Every message you send is archived in the InTouch database. Clicking the Message Archive link takes you to a screen where you can view these messages and delete them from the archive if you choose.

Users and Groups

The InTouch application comes complete with a database-driven user/group/permission system. At the very least, you can use this to add users who can access the InTouch administrator. To do this, simple add a new user (by clicking the New User link, entering the user's contact information, then either giving them Administrator permissions or adding them to the Administrator group and clicking the Edit This User button).

Additionally, this user database can store users who can build e-mail lists. This is up to you. Adding, editing, and deleting users is done the same way as the other data in this application.

The Permissions section allows you to add, rename, and delete permission levels. If this is done, a developer will need to implement permissions in the ColdFusion code to allow/deny access to different permission levels.

Much as in other security systems, InTouch allows you to create groups. A group can then be given different levels of permission. Because there really is only one permission and one group—those who can access the administrator—this is a core system that can be edited and updated by your development team.

InTouch Services: Subscribe and Unsubscribe

The {intouch_root}/services/subscriptions.cfc component provides services that can be used to subscribe and unsubscribe users. This was done for maximum flexibility, so you can call these services from either a ColdFusion processing page or any other application development environment that supports SOAP-based web services (this includes Microsoft .NET and J2EE, among many others). Take a look at the definitions of these services, using the ColdFusion CFC browser:

subscribe

remote boolean subscribe ( required numeric UserID, required numeric ListID, string Format="[runtime expression]" )

Use this function to subscribe a user to a list.

Output: suppressed

Parameters:
UserID: numeric, required, UserID - This should be the UserID that relates to the user table specified in the InTouch administrator.
ListID: numeric, required, ListID - This should be the ListID that relates to the list in the InTouch administrator.
Format: string, optional, Format - This optional argument allows you to specify Text or HTML for preferred email format.

unsubscribe

remote boolean unsubscribe ( required numeric UserID, required numeric ListID )

Use this function to unsubscribe a user from a list.

Output: suppressed

Parameters:
UserID: numeric, required, UserID - This should be the UserID that relates to the user table specified in the InTouch administrator.
ListID: numeric, required, ListID - This should be the ListID that relates to the list in the InTouch administrator.

You can see there are two methods available:

  • The subscribe() method subscribes a user to a list and specify their preferred format (text or HTML). You must pass UserID, ListID, and the format (either Text or HTML).
  • The unsubscribe() method unsubscribes a user from a list. This method requires UserID and ListID.

Both methods return "true" if successful and "false" if there is a failure.

These can be exposed as web services and called on by referring to the WSDL located at {intouch_root}/services/subscriptions.cfc?wsdl. Otherwise, you can invoke them as CFCs using the following syntax (assuming that intouch is the root folder of the InTouch application, otherwise use dot syntax in the component attribute to specify the folder path):

<cfinvoke 
 component="intouch.services.subscriptions"
 method="subscribe"
 returnvariable="subscribeRet">
   <cfinvokeargument name="UserID" value="enter_value_here"/>
   <cfinvokeargument name="ListID" value="enter_value_here"/>
</cfinvoke>

<cfinvoke 
 component="intouch.services.subscriptions"
 method="unsubscribe"
 returnvariable="unsubscribeRet">
   <cfinvokeargument name="UserID" value="enter_value_here"/>
   <cfinvokeargument name="ListID" value="enter_value_here"/>
</cfinvoke>

The InTouch Architecture

The InTouch architecture uses the simple application framework from Veraison, LLC. The root folder structure contains the following subfolders:

  • /content: HTML files for static content pages
  • /database: Should be moved outside of root
  • /images: Site images
  • /includes: ColdFusion templates, optionally moved outside of root
  • /services: CFCs and web services
  • /style: Headers, footers, and style sheets

This is a basic method for breaking up different types of data—and providing a clear separation of content, design, and functionality. The content contains HTML files that can be accessed by content owners. The images and style directories can be accessed by designers. The includes and services directories can be accessed by ColdFusion programmers. It would even be possible to place these directories (except for the images folder) below the web root and map them in the ColdFusion Administrator. This provides extra security by keeping code and templates inaccessible from the web server.

In the root folder, Application.cfm serializes data into the application scope by reading the application.wddx file in the includes folder. Then index.cfm serves as the master controller for the application. All files are accessed from this central page by specifying an action in the URL (index.cfm?action=ActionName). The action name is the name of the ColdFusion template in the includes folder without the .cfm ending. For example, if you wanted to access the /includes/groups.cfm functionality, you would enter /index.cfm?action=groups. The index.cfm file handles authentication and includes the header and footer.

Additionally, authenticate.cfm provides the security check using cflogin and retrieving the user, groups, and permissions information from the database. Login.cfm is the login form.

The InTouch Database

Figure 3 shows the entity relationship diagram of the InTouch database.

The InTouch database's entity relationship diagram

Figure 3. The InTouch database's entity relationship diagram

A few things are worth noting here:

  • Users/Groups/Permissions all relate in many-to-many fashion using the GroupsPermissions and UserPermissions tables. This allows users to belong to many groups, groups to have many permissions, and so forth.
  • The Users table does not enforce the relationship between it and the Lists table. This is because the application allows for linking external user information. You can see that the Lists table includes the DSN, UserTable, UserID, and UserEmail fields. The application, not the database, enforces and activates the relationship between this table, the ListsUsers table, and the external database.
  • The ListsUsers table includes the following: ListID (relating to the appropriate list), UserID (relating to the external or internal user DSN as specified in the related List row), Format (Text or HTML), Unsubscribe (flags when a user wants to be removed from the list), and UnsubscribeDate (records the date and time a user is unsubscribed). There is one row in this table for every instance of every user in every list. A single user can have multiple rows in this table.
  • Templates stores the templates.
  • MessageArchives (top right) stores the messages after they are sent.

Listing, Updating, and Deleting Pages

One of the primary aspects of any database application is invariably to add, delete, and update information. In this application, this is done for the following database information:

  • Users
  • Groups
  • Permissions
  • Templates
  • Lists

The basic setup for each uses the following files ("xxx" is the name of the information being edited—for example, lists.cfm, groups.cfm, and so on):

  • xxx.cfm: This page lists information. Clicking on an item brings up the edit page; checking the box and clicking the Delete button deletes the selected items.
  • xxx-edit.cfm: This page will be the add and update page for each item. If an ID value is passed, the information will be loaded into the form and a hidden field with the ID value will be added to the page, otherwise it will be an empty insert form.
  • xxx-editproc.cfm: This page will process either the update or the insert query, depending on whether the ID field was passed.
  • xxx-delete.cfm: This page will process the delete query by looping through the ID values passed from the list page.

Getting Returned E-mails

One of the cool things InTouch does is return e-mails to the address entered in the Global Settings screen so you can easily remove them from the list. Take a look at the bademails.cfm template. E-mails are retrieved using <CFPOP>:

<cfpop action="getheaderonly" 
               server="#application.ReplyEmailMX#" 
   username="#application.ReplyEmail#" 
   password="#application.ReplyEmailPass#" 
   name="getReplies">

This returns a query object that is then looped through and output on the page. The administrator can check a box and submit the form. Doing so loops through any checked e-mail submitted and removes users from the list—basically by unflagging the Unsubscribe field and entering the current date/time in the UnsubscribeDate field, although it gets a bit more complex than that.

You can see this looping in the ColdFusion code at the top of the template. Note how first the information between < and > is removed. This is done in the case of e-mails having the format "Drew Falkman" info@veraison.info.

Next, the user database information is retrieved for all lists in the database. We then loop through the results of this query and look for user IDs that have a matching e-mail using this query:

<cfquery datasource="#getDSN.DefaultUserDSN#" name="getUserID">
  SELECT #getDSNs.DefaultUserID# 
  FROM #getDSNs.DefaultUserTable#
  WHERE #getDSNs.DefaultUserEMailField# = '#actualEmailAddress#'
</cfquery>

Note the usage of the dynamic user database information for the datasource attribute in every line of the SQL query. If no query object exists, you can assume that there was an error: This query is executed in a <CFTRY> that has an empty <CFCATCH> block, which allows for errors to occur without giving an error message. In such cases, you then use the default information stored in the application scope (as set in the global settings area).

When you're done with all this, you can delete the e-mail from the mail server:

<cfpop action="delete" 
            server="#application.ReplyEmailMX#" 
   username="#application.ReplyEmail#" 
   password="#application.ReplyEmailPass#">
   

Sending Messages

Now we come to the heart of the InTouch system: sending e-mails. The following steps are completed in the same template: messages-new.cfm. Note at the top of the template that a local variable is set to denote the current step:

<!--- look for form vars and set steps, if necessary --->
<cfif IsDefined("FORM.HTMLTemplate")>
  <cfset messageStep = 1>
</cfif>
<cfif IsDefined("FORM.HTMLMessage")>
  <cfset messageStep = 2>
</cfif>
<cfif IsDefined("FORM.ListID")>
  <cfset messageStep = 3>
</cfif>

By this definition, the first step would be 0: The variable won't be defined. Below we use a set of <CFIF> and <CFELSEIF> blocks to process information (if necessary) and display information for the current step as defined in this block. Let's take a look at the steps involved.

Step 1: Select the Template

This is the simplest step in the process. If the messageStep variable does not exist, this page will appear with two drop-down lists: one containing all text-formatted messages and one containing all HTML-formatted messages in the Templates table. The user selects (or not) a template for each format and proceeds to the next step.

Step 2: Compose the Message

This page performs no processing, except that it retrieves any template text based on templateIDs passed from the first step and outputs the template (Text or HTML) to the appropriate textarea field: TextMessage or HTMLMessage. The user enters the Subject and edits the Text and HTML messages.

Here the user can enter fields from the user database that they want to output into the message as it gets sent to each user. This is done by surrounding field names with percent signs. For example, %CompanyName% outputs the value of the CompanyName field in each message sent out.

Step 3: Preview the Message

In this step you first set the message information to the SESSION scope. This allow you to output the information to the preview window and carry it over to the next page where it will be sent. Additionally, a multiple select field contains all lists from the database for the user to choose from.

Step 4: Send the Messages

This final step is invariably the most complex. The code shows this to be a <CFSCRIPT> block. The first step is to isolate any dynamic fields that were entered in the e-mail text (both text and HTML versions). Note that a WHILE loop iterates through the message. Then use a regular expression to find dynamic fields:

REFindNoCase("%[A-Za-z0-9_]+%",session.TextMessage,ii,"True")

The REFindNoCase() method uses a regular expression to find something in a message without comparing its case. The regular expression is the first argument. The percent signs are on the outside and the text bracket [] includes the characters allowed—you can use both uppercase and lowercase letters as well as numbers and the underscore (_) character. The plus sign means it can accept more than one character between the percent signs.

Once you have set them to a list, remove the percent signs using the Replace() function and replace "%" with "", an empty string. The pos[x] and len[x] arrays are set as the results of a regular expression function. Because each loop only finds one result, you can always find the values in the first position of the array. The pos[1] array returns the number where the substring is located and len[1] returns the number of characters in the substring. See the ColdFusion documentation for more information on using regular expressions and related functions.

The process is repeated for the HTML message; it is possible to have different fields in each message. Now you have a list of fields to grab from the user database: FieldList.

Next, you loop through the lists that the user passed from the previous page: FORM.ListID. Note that throughout this looping you use <CFFLUSH> to output information to the screen so the user can see the processing as it occurs.

Get the user database information—either from the list table for the current list or from the application scope (the defaults). Then get the UserID and the format for everyone in the current list. Note the first query that retrieves the dynamic information and user e-mail after you retrieve the UserIDs:

<cfquery datasource="#UserDSN#" name="getEmailList">
  SELECT #UserEMail#,#FieldsList#, #UserID# as thisUserID
  FROM #UserTable#
  WHERE #UserID# IN (#valuelist(getUserList.UserID)#)
</cfquery>

This is done for each list; the IN statement uses the valuelist() function to output every UserID for each list as a list. You can output FieldsList as is because it is already a list of field names separated by commas. This is also done in a <CFTRY> block: In case the user enters a bad fieldname, <CFCATCH> will catch this process before the e-mails are sent out for any list.

Finally, you loop through this query and send an e-mail to each user. The format is obtained by a simple query of a query on the original query that had the UserID and formats. Sending out the actual e-mails is handled by a simple <CFMAIL>; either the type is set to HTML or it is not.

Although InTouch is a solid little application, it is just a starting point. Because the architecture is open and adaptable, you should be able to integrate it easily into your web application environment and customize it to suit your needs. Good luck and happy e-mailing!